package com.soar.tbox.util;

import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

import com.soar.tbox.Constants;

/**
 * 日志输出
 * 
 * @author songjunjie
 * 
 */
public class LogUtil {
	private static String logfile = "";// 普通日志文件
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/* 创建日志文件 */
	static {
		logfile = Constants.SDPATH + File.separator + Constants.LOG_PATH
				+ File.separator + "tboxInfo.log";
		File logdir = new File(Constants.SDPATH + File.separator
				+ Constants.LOG_PATH);
		if (!logdir.exists()) {
			logdir.mkdir();
		}
		File file = new File(logfile);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 输出日志
	 * 
	 * @param log
	 */
	public static synchronized void info(String bizName, String log) {
		FileWriter fw = null;
		try {
			fw = new FileWriter(logfile, true);
			String date = sdf.format(new Date());
			StringBuilder sb = new StringBuilder();
			for(int i=0;i<bizName.length();i++){
				sb.append("-");
			}
			sb.append("---------------------\r\n");
			sb.append("|").append(date + " " + bizName).append("|\r\n");
			StringTokenizer st = new StringTokenizer(log, "\r\n");
			int maxLen = 0;
			while (st.hasMoreTokens()) {
				String line = st.nextToken();
				int len = line.length();
				if(line.indexOf("\t")>-1){
					len += 8;
				}
		        if(maxLen < len){
		        	maxLen = len;
		        }
		     }
			StringBuilder cutoff = new StringBuilder(maxLen);
			for(int i=0;i<maxLen;i++){
				cutoff.append("-");
			}
			cutoff.append("\r\n");
			sb.append(cutoff);
			sb.append(log);
			sb.append(cutoff);
			fw.append(sb);
			fw.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 错误日志输出
	 * @param info
	 * @param e
	 */
	public static synchronized void error(String info, Throwable e) {
		CharArrayWriter buf = new CharArrayWriter();
		PrintWriter writer = new PrintWriter(buf);
		e.printStackTrace(writer);
		String date = sdf.format(new Date());
		String error = buf.toString();
		FileOutputStream out = null;
		PrintWriter pw = null;
		try {
			out = new FileOutputStream(logfile, true);
			pw = new PrintWriter(out);
			pw.print("[" + date + "]" + info + "\r\n" + error);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}finally{
			if(pw != null){
				pw.close();
			}
		}
	}
}
